package com.ruoyi.system.service.impl;

import com.ruoyi.common.core.domain.entity.LmSysUser;
import com.ruoyi.system.mapper.LmSysUserMapper;
import com.ruoyi.system.service.ILmSysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class LmSysUserServiceImpl implements ILmSysUserService {
    private static final Logger log = LoggerFactory.getLogger(LmSysUserServiceImpl.class);

    @Autowired
    private LmSysUserMapper userMapper;

    @Override
    public LmSysUser getLmSysUserByUsername(String username) {
        return userMapper.selectUserByUsername(username);
    }

    @Override
    public LmSysUser login(String username, String md5Password) {
        LmSysUser user = userMapper.selectUserByUsername(username);
        if (user != null && user.getPassword().equals(md5Password)) {
            // 更新最后登录时间和IP
            user.setLastLoginTime(LocalDateTime.now());
            userMapper.updateUser(user);
            return user;
        }
        return null;
    }

    @Override
    public void updateById(LmSysUser user) {
        user.setUpdateTime(LocalDateTime.now());
        userMapper.updateUser(user);
    }

    @Override
    public LmSysUser getById(long loginIdAsLong) {
        return userMapper.selectUserById(loginIdAsLong);
    }

    @Override
    public List<LmSysUser> getAdminList(Integer page, Integer limit, String account, Integer status) {
        LmSysUser user = new LmSysUser();
        if (account != null && !account.trim().isEmpty()) {
            user.setUsername(account);
        }
        if (status != null) {
            user.setStatus(status);
        }
        List<LmSysUser> userList = userMapper.selectUserList(user);
        return userList;
    }

    @Override
    public void save(LmSysUser sysUser) {
        if (sysUser.getId() == null) {
            // 新增
            sysUser.setCreateTime(LocalDateTime.now());
            userMapper.insertUser(sysUser);
        } else {
            // 更新
            sysUser.setUpdateTime(LocalDateTime.now());
            userMapper.updateUser(sysUser);
        }
    }

    @Override
    public void removeById(Integer id) {
        userMapper.deleteUserById(Long.valueOf(id));
    }
}
